import { Component, OnInit } from '@angular/core';
import { EventService } from 'services/event-service';
import { AuthService } from 'services/auth-service';
import { Router } from '@angular/router';
import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';
import { MdlDatePickerService } from '@angular-mdl/datepicker';
import { Observable } from 'rxjs/Observable';
import * as moment from 'moment';
import { SessionService } from 'services/session-service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DOMAIN, API_VERSION } from 'app.config';

@Component({
    selector: 'app-event-component',
    templateUrl: './event-component.component.html',
    styleUrls: ['./event-component.component.scss'],
    providers: [EventService, AuthService, MdlDatePickerService]
})
export class EventComponentComponent implements OnInit {
    public startDate: any;
    public endDate: any;

    public count: number = 0;
    public offset: number = 0;
    public limit: number = 10;
    public deleteId: number = 0;
    public isPageLoading: boolean = false;
    public rows = [];
    public pagerMessage = {
        emptyMessage: '没有数据',
        totalMessage: '总计'
    };
    public columns = [
        { name: '性别', prop: 'gender' },
        { name: '年龄', prop: 'age' },
        { name: '质量', prop: 'quality' },
        { name: '抓拍时间', prop: 'timestamp' },
        { name: '抓拍照片', prop: 'photo' }
    ];
    constructor(
        private _eventService: EventService,
        private _authService: AuthService,
        private _router: Router,
        private _dialogService: MdlDialogService,
        private _sessionService: SessionService,
        private _snackBarService: MdlSnackbarService,
        private _datePicker: MdlDatePickerService,
        private _http: HttpClient
    ) {}

    async ngOnInit() {
        // const ret = await this._eventService.searchEvents();
        // console.log(ret);
        this.page(this.offset, this.limit);
    }
    public async pickAStartDate($event: MouseEvent) {
        const selectedDate: Date = await this._datePicker
            .selectDate(this.startDate, { openFrom: $event })
            .toPromise();
        this.startDate = selectedDate ? moment(selectedDate) : null;
        await this.page(0, null);
    }
    public async pickAEndDate($event: MouseEvent) {
        const selectedDate: Date = await this._datePicker
            .selectDate(this.endDate, { openFrom: $event })
            .toPromise();
        this.endDate = selectedDate ? moment(selectedDate) : null;
        await this.page(0, null);
    }
    _constructQuery() {
        const criteria: any = {};
        if (this.startDate) {
            criteria.start = this.startDate;
        }
        if (this.endDate) {
            criteria.end = this.endDate;
        }
        // if (this._sessionService.isUserProperty) {
        //     criteria.projectId = this._sessionService.Managable.id;
        // }
        return criteria;
    }

    async page(offset, limit) {
        this.isPageLoading = true;
        try {
            const criteria: any = this._constructQuery();
            criteria.page = offset + 1;
            criteria.size = this.limit;
            let searchRet: any = await this._eventService.searchEvents(
                criteria
            );
            this.count = searchRet.page.count;

            const start = offset * limit;
            const end = start + limit;
            const rows = [...this.rows];

            for (let i = start; i < end; i++) {
                rows[i] = searchRet.data[i - start];
            }
            // searchRet.data.forEach(d => {
            //     d.timespan = new Date(d.timespan);
            // });
            // this.rows = rows;
            this.rows = searchRet.data;
            this.isPageLoading = false;
            console.log('Page Results', start, end, rows);
        } catch (e) {
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
            this.isPageLoading = false;
        }
    }

    public async getInactiveUser(event) {
        const projectId = this._sessionService.Managable.id;
        location.href = `${DOMAIN}/api/${API_VERSION}/visit_log/${Math.random()}?projectId=${projectId}`;
    }

    onPage(event) {
        console.log('Page Event', event);
        this.page(event.offset, event.limit);
    }
}
